package com.service.other;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Logger {
	/**
	 * 打印输出日志
	 * @param obj 日志信息
	 * @param isSave 是否存储到文件
	 */
	public static void err(Object obj) {
		String msg = null;
		if(obj instanceof Throwable){
			msg = getExceptionMsg(obj);
		}else{
			StringBuilder builder = new StringBuilder();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			builder.append(MessageFormat.format("error at time : {0} \r\n",format.format(new Date())));
			builder.append(String.valueOf(obj)+"\r\n");
			msg = builder.toString();
		}
		if(msg!=null){
			System.err.print(msg);
			append(getSavePath(new Throwable()), msg);
		}
	}
	
	public static String getExceptionMsg(Object obj){
		StackTraceElement[] stackElements = ((Exception)obj).getStackTrace();
		if (stackElements != null) {
			StringBuilder builder = new StringBuilder();
			builder.append(MessageFormat.format("error msg : {0} \r\n",((Exception)obj).getMessage()));
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			builder.append(MessageFormat.format("error at time : {0} \r\n",format.format(new Date())));
			for(StackTraceElement ste : stackElements){
				builder.append(MessageFormat.format("at {0}.{1}({2}:{3})\r\n",ste.getClassName(),ste.getMethodName(),ste.getFileName(),ste.getLineNumber()));
			}
			return builder.toString();
		}
		return null;
	}

	/**
	 * 打印输出日志
	 * @param obj 日志信息
	 * @param isSave 是否存储到文件
	 */
	public static void println(Object obj) {
		Date logdate = new Date();
		System.out.print(MessageFormat.format("at time {0} : {1} \r\n",logdate,String.valueOf(obj)));
	}
	
	public static void debug(String deviceNo, String message) {
		append(getDebugDataSavePath(deviceNo),
				"At " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \r\n" + message);
		System.out.println(message);
	}
	
	private static String getSavePath(Throwable ex){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		StackTraceElement[] stackElements = ex.getStackTrace();
		if (stackElements != null) {
			String className = stackElements[1].getClassName();
			return ServerConfig.instance().log_savepath + File.separator + format.format(new Date()) + File.separator + className + ".txt";
		}else{
			return ServerConfig.instance().log_savepath + File.separator + format.format(new Date()) + File.separator + "Exception.txt";
		}
	}
	
	private static String getDebugDataSavePath(String deviceNo) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return ServerConfig.instance().debug_savepath + File.separator + format.format(new Date()) + File.separator
				+ deviceNo + ".txt";
	}
	
	private static void append(String path, String content) {
		RandomAccessFile randomFile = null;
		try {
			File file = new File(path);
			File folder = new File(file.getParent());
			if (!folder.exists()) {
				folder.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			randomFile = new RandomAccessFile(path, "rw");
			long fileLength = randomFile.length();
			randomFile.seek(fileLength);
			randomFile.write(content.getBytes());
			randomFile.write("\r\n".getBytes());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (randomFile != null) {
				try {
					randomFile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
